package com.example.interceptor;

import cn.hutool.json.JSONUtil;
import com.example.common.enums.KeyEnum;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.exception.CustomException;
import com.example.constant.JwtClaimsConstant;
import com.example.context.BaseContext;
import com.example.pojo.entity.Admin;
import com.example.pojo.utils.LoginUser;
import com.example.properties.JwtProperties;
import com.example.utils.IpUtils;
import com.example.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * jwt令牌校验的拦截器
 *
 * @author ding
 * @since 2024/7/23
 */
@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (request.getRequestURI().equals("/login") || request.getRequestURI().equals("/validSms")){
            //调用登录方法
            String ip = IpUtils.getIp();
            //UV中新增相关数据
            redisTemplate.opsForHyperLogLog().add(KeyEnum.UV, ip);
            //当前在线人数中新增数据
            redisTemplate.opsForSet().add(KeyEnum.ONLINE, ip);

            filterChain.doFilter(request, response);
            return;
        }

        if (request.getRequestURI().equals("/logOut")){
            //如果调用退出方法，说明当前用户退出了系统
            String ip = IpUtils.getIp();
            //将该ip数据从redis中删除
            redisTemplate.opsForSet().remove(KeyEnum.ONLINE, ip);
        }

        //从请求头中获取token
        String token = request.getHeader("token");
        //没有token
        if (!StringUtils.hasLength(token)){
            //放行，因为后面的会抛出响应的异常 401 403
            filterChain.doFilter(request, response);
            return;
        }

        //有token
        Integer userId;
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            Long adminId = Long.valueOf(claims.get(JwtClaimsConstant.ADMIN_ID).toString());
            //在线程中设置当前登录的ID
            BaseContext.setCurrentId(adminId);

            userId = Math.toIntExact(adminId);
        }catch (Exception e){
            e.printStackTrace();
            throw new CustomException(ResultCodeEnum.TOKEN_INVALID_ERROR);
        }

        //从redis中获取用户信息
        String redisKey = KeyEnum.TOKEN + "_" + userId;
        Object obj = redisTemplate.opsForValue().get(redisKey);
        if (Objects.isNull(obj)){
            throw new CustomException(ResultCodeEnum.TOKEN_CHECK_ERROR);
        }

        Admin admin = JSONUtil.toBean(obj.toString(), Admin.class);
        LoginUser loginUser = new LoginUser(admin);
        //将Authentication对象(用户信息、已认证状态、权限信息)存入SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //放行
        filterChain.doFilter(request, response);
    }
}
